package cn.org.xwb.bookmall.user.service.impl;

import cn.org.xwb.bookmall.user.service.RsaService;
import cn.org.xwb.common.encrypt.dto.RsaKeyPair;
import cn.org.xwb.common.model.vo.RespResult;
import cn.org.xwb.common.utils.HttpUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * RSA 相关的业务层
 */
@Service
@Log4j2
public class RsaServiceImpl implements RsaService {

    /**
     * 通用的 RSA 密钥对
     */
    @Autowired
    private RsaKeyPair rsaKeyPair;

    /**
     * 向客户端发送通用的 RSA 公钥
     *
     * @return 通用的 RSA 公钥
     */
    @Override
    public RespResult<Object> rsaPublicKey(HttpServletRequest request) {
        String rsaPublicKey = rsaKeyPair.getPublicKey();
        if (Objects.isNull(rsaPublicKey) || rsaPublicKey.isEmpty()) {
            log.error("客户端 {} 获取 RSA 公钥失败，原因：RSA 公钥为空", HttpUtil.getClientHostIpPort(request));
            return RespResult.fail("获取 RSA 公钥失败");
        }
        log.info("客户端 {} 获取 RSA 公钥成功", HttpUtil.getClientHostIpPort(request));
        return RespResult.success("获取 RSA 公钥成功", rsaPublicKey);
    }
}
